<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="queryParams.roleName" :placeholder="'请输入角色名称'" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :empty-text="'无数据'"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="roleName" align="center" label="角色名称" />
      <el-table-column prop="roleDesc" align="center" label="角色描述" />
      <el-table-column prop="createTime" value-format="yyyy-MM-dd" align="center" label="创建时间" />
      <el-table-column prop="updateTime" value-format="yyyy-MM-dd" align="center" label="更新时间" />
      <el-table-column :label="'操作'" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="'用户角色'" prop="roleName">
          <el-input v-model="temp.roleName" :placeholder="'请输入角色名称'" @keyup.enter.native="dialogStatus==='create'?createData():updateData()" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="temp.roleDesc"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item :required="true" label="菜单">
          <el-tree class="tree-border" ref="tree" :data="routesData" :default-checked-keys="ids" :props="defaultProps" show-checkbox node-key="id" default-expand-all />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { addRole, delRole, getRoleList, updateRole } from '@/api/role'
import waves from '@/directive/waves'
import { getRoleMenu, getRoleMenuCheckedKeys } from '@/api/menu'
import { updateRoleMenu } from '@/api/rolemenu'

export default {
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      queryParams: {
        roleName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑角色',
        create: '添加角色'
      },
      temp: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [{ required: true, message: '角色名称必填', trigger: 'blur' }]
      },
      // 选中的菜单列表
      ids:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      routesData: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    handleFilter() {
      this.getRoleList()
    },
    // 获取角色列表
    getRoleList() {
      this.listLoading = true
      getRoleList(this.queryParams).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    // 获取菜单列表
    getRoleMenu(){
      getRoleMenu().then(response => {
        this.routesData = response.data
      })
    },
    getRoleMenuCheckedKeys(id){
      getRoleMenuCheckedKeys(id).then(response => {
        this.ids = response.data
      })
    },
    resetTemp() {
      this.temp = {
        roleName: '',
        roleDesc: ''
      }
    },
    handleCreate() {
      this.getRoleMenu()
      this.ids = []
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getRoleMenu()
      this.getRoleMenuCheckedKeys(this.temp.id)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(row.id).then(response => {
          this.getRoleList()
          this.$notify({
            title: '成功',
            message: '删除角色成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$notify({
          title: '成功',
          message: '已取消删除',
          type: 'success',
          duration: 2000
        })
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addRole(this.temp).then(response => {
            this.getRoleList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加角色成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateRole(tempData).then(response => {
            updateRoleMenu(tempData.id,this.$refs.tree.getCheckedKeys()).then(res => {
              this.getRoleList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '修改角色成功',
                type: 'success',
                duration: 2000
              })
            })
          })
        }
      })
    }
  }
}
</script>

